package com.yao.controller;

import com.yao.context.BaseContext;
import com.yao.pojo.ChangeUser;
import com.yao.pojo.Result;
import com.yao.pojo.User;
import com.yao.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/user")
@Validated
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result userRegister(@RequestBody User user){
        log.info("用户注册...{}",user);

        Boolean userRegitserFlag = userService.userRegister(user);
        if (userRegitserFlag) return Result.success("注册成功");
        return Result.error("用户已存在");
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result userLogin(@RequestBody User user){
        log.info("用户登录...{}",user);

        String token = userService.userLogin(user);
        if (!(StringUtils.hasLength(token))) return Result.error("用户名或密码错误");
        return Result.success(token);
    }

    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation("获取用户个人信息")
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        log.info("用户信息ID: ...{}", BaseContext.getCurrentId());

        User user = userService.getUserInfo();
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @ApiOperation("修改用户信息")
    @PutMapping("/update")
    public Result changeUserInfo(@RequestBody User user){
        log.info("修改用户的信息...{}",user);

        userService.changeUserInfoByUserId(user);
        return Result.success("修改成功");
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @ApiOperation("修改用户密码")
    @PatchMapping("/updatePwd")
    public Result changeUsernameAndPassword(@RequestBody ChangeUser user){
        log.info("修改用户的信息...{}",user);

        Boolean flag = userService.changeUserPassword(user);
        if (flag) return Result.success("修改成功");
        return Result.error("二次密码不一致");
    }
}





